<?php
namespace app\admin\controller;

use app\common\model\Usercoupon as UsercouponModel;
use app\common\controller\AdminBase;
use think\Config;
use think\Session;
use think\Db;

class Usercoupon extends AdminBase
{
    protected $usercoupon_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->usercoupon_model = new UsercouponModel();
    }

    /**
     * 管理
     * @param string $keyword
     * @param int    $page
     * @return mixed
     */
    public function index($keyword_name = '',$keyword_phone = '',$keyword_coupon = '', $page = 1)
    {
        $map = [];
        if ($keyword_name) {
            $map['userName'] = ['like', "%{$keyword_name}%"];
        }
        if ($keyword_phone) {
            $map['userPhone'] = ['like', "%{$keyword_phone}%"];
        }
        if ($keyword_coupon) {
            $map['couponName'] = ['like', "%{$keyword_coupon}%"];
        }
        $user_list = Db('user')->where('status',1)->select();
        $coupon_list = Db('coupon')->where('status',1)->select();
        $usercoupon_list = $this->usercoupon_model->where($map)->order('id DESC')->paginate(15, false, ['page' => $page]);

        return $this->fetch('index', ['usercoupon_list' => $usercoupon_list, 'keyword_name' => $keyword_name,'keyword_phone' => $keyword_phone,'keyword_coupon' => $keyword_coupon,'user_list' => $user_list,'coupon_list' => $coupon_list]);
    }

    /**
     * 删除
     * @param $id
     */
    public function delete($id = 0, $ids = [])
    {
        $id = $ids ? array_merge($ids) : $id;
        if ($id) {
            if ($this->usercoupon_model->destroy($id)) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('请选择需要删除的内容');
        }
    }

    public function uses($id){
        $usercoupon = $this->usercoupon_model->find($id);

        return $this->fetch('uses', ['usercoupon' => $usercoupon]);
    }

    public function bidv($id){
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'usercoupon');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $yruuju = $this->usercoupon_model->where('id',$id)->find();
                if($data['coding'] == $yruuju['coding']){
                    $yruuju->uses = '0';
                    $yruuju->usesDate = date('Y-m-d H:i:s',time());
                    $yruuju->disposeMan = Session::get('admin_name');
                    if ($yruuju->save() !== false) {
                       $this->success('使用成功');
                    } else {
                        $this->error('使用失败');
                    }
                }else{
                    $this->error('输入券码有误,请重新输入');
                }
            }
        }
    }
    
}